import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/model/patrol/patrol_task_model.dart';
import 'package:ls_work/sql/AppDbUtils.dart';
import 'package:ls_work/sql/protral/patrol_task_entity.dart';
import 'package:ls_work/ui/patrol/offline_patrol_detail_page.dart';
import 'package:ls_work/ui/patrol/patrol_record_list_page.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/viewmodel/patrol/patrol_nfc_write_view_model.dart';
import 'package:nfc_manager/nfc_manager.dart';

import '../../message/message_config.dart';
import '../../ui/patrol/offline_task_record_page.dart';
import '../../util/utils.dart';

class OfflinePatrolListViewModel extends BaseViewModel {
  OfflinePatrolListViewModel(BuildContext context) : super(context);

  var model = PatrolTaskModel();

  var hasLocalTask = false;

  List<PatrolTaskData> taskList = [];

  num unFinishNum = 0;

  Future<void> getOfflineTask() async {
    var localRecord = await model.getLocalRecord();
    if (localRecord.isNotEmpty) {
      showToast("当前有未提交记录，请先提交");
      return;
    }

    showLoadingState();
    try {
      var data = await model.getOfflineTask();
      if (data.taskList.isEmpty) {
        showApplyDialog(context: context, onSubmit: () {}, message: "未获取到线上任务");
        showEmptyState();
        return;
      }
      showLoadingDialog(msg: "正在保存任务数据");
      await model.deleteAll();
      await model.insetTask(data);
      hideDialog();
      await getLocalTask();
      showContent();
    } catch (e) {
      print(e);
      showToast(NetErrorUtils.getNetError(e));
      showErrorState(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  Future<void> getLocalTask() async {
    taskList = await model.getLocalTask();
    taskList.sort((a, b) {
      return a.startDate!.compareTo(b.startDate!);
    });
    await calculateUnFinish();
    notifyListeners();
  }

  Future<void> calculateUnFinish() async {
    var list = await AppDbUtils.instance().patrolTaskDao.getAllTaskPoint();
    var number = 0;
    for(var item in list){
      if(!((item.status??0)==1||!item.executeDate.isNullOrEmpty())){
        number++;
      }
    }
    unFinishNum = number;
    notifyListeners();
  }

  @override
  void onCreated() {
    super.onCreated();
    _init();
  }

  Future<void> _init() async {
    await getLocalTask();
  }

  Future<void> scanCode() async {
    var code = await Utils.scan();
    if (!code.isNullOrEmpty()) {
      _scanResult(code);
    }
  }

  Future<void> startNfc() async {
    var nfcEnable = await NfcManager.instance.isAvailable();
    if (nfcEnable) {
      NfcManager.instance.startSession(
          onDiscovered: (NfcTag tag) async {
            Ndef? ndef = Ndef.from(tag);
            if (ndef?.cachedMessage?.records.isNotEmpty ?? false) {
              var payload = ndef?.cachedMessage?.records[0].payload;
              var str = String.fromCharCodes(
                payload!,
                3,
              );
              if (taskList.isEmpty) {
                NfcManager.instance.stopSession();
                return;
              }
              if (!str.isNullOrEmpty()) {
                _scanResult(str);
              }
            }
            NfcManager.instance.stopSession();
          },
          onError: (error) async {},
          alertMessage: "准备扫描，将标签贴近手机");
    } else {
      showToast("当前机型不支持nfc");
    }
  }

  Future<void> _scanResult(String code) async {
    var resultMap = await Utils.decodeQrcode(code);
    if (resultMap != null && resultMap['type'] == '11') {
      var localTaskPoint = await model.searchTaskPointByQrcode(code);
      if (localTaskPoint != null && localTaskPoint.isNotEmpty) {
        Go().push(OfflinePatrolDetailPage(code));
      } else {
        showToast("当前时间无可执行任务");
      }
    } else {
      showToast("请扫描巡防点二维码");
    }
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if (event.msgCode == MessageConfig.REFRESH_PATROL) {
      _init();
    }
    if (event.msgCode == MessageConfig.NFC_READ_MESSAGE) {
      _scanResult(event.obj);
    }
  }

  void selectRecordType() {
    showBottomSelect(context, items: ['线上记录', '离线记录'], onSelect: (str) {
      if (str == '线上记录') {
        Go().push(PatrolRecordListPage());
      }
      if (str == '离线记录') {
        Go().push(OfflineTaskRecordPage());
      }
    });
  }
}
